﻿/*
 * @author: wizardc
 */

using System.Collections.Generic;
using UnityEngine;

#if UNITY_EDITOR
using UnityEditor;
#endif

namespace Dou.UI
{
    /// <summary>
    /// TMP 字体材质管理器
    /// </summary>
    public sealed class TMPFontMatMgr
    {
        private static TMPFontMatMgr _instance;
        public static TMPFontMatMgr instance => _instance ??= new TMPFontMatMgr();

        private Dictionary<string, Material> _map = new Dictionary<string, Material>();

        private TMPFontMatMgr()
        {
#if UNITY_EDITOR
            EditorApplication.playModeStateChanged += (state) =>
            {
                _map.Clear();
            };
#endif
        }

        public Material GetMaterial(FontSetting fontSetting, TextMeshProParam param)
        {
            var key = GetKey(fontSetting, param);
            if (_map.ContainsKey(key))
            {
                return _map[key];
            }

            var mat = GameObject.Instantiate(fontSetting.mat == null ? fontSetting.font.material : fontSetting.mat);

            mat.SetColor("_FaceColor", param.faceColor);
            if (mat.HasProperty("_FaceSoftness"))
            {
                mat.SetFloat("_FaceSoftness", param.faceSoftness);
            }

            mat.SetFloat("_FaceDilate", param.faceDilate);

            if (param.useOutLine)
            {
                mat.EnableKeyword("OUTLINE_ON");
                mat.SetColor("_OutlineColor", param.outLineColor);
                mat.SetFloat("_OutlineWidth", param.outLineWidth);
            } else
            {
                mat.DisableKeyword("OUTLINE_ON");
            }

            _map.Add(key, mat);
            return mat;
        }

        private string GetKey(FontSetting fontSetting, TextMeshProParam param)
        {
            return $"{fontSetting.GetInstanceID()}_{param.faceColor}_{param.faceSoftness}_{param.faceDilate}_{param.useOutLine}_{param.outLineColor}_{param.outLineWidth}";
        }
    }
}
